import {EyeInvisibleOutlined, EyeTwoTone, UserOutlined, LockOutlined} from "@ant-design/icons";
import {Button, Card, Form, Input} from "antd";
import {connect} from "react-redux";
import {useState} from "react";
import {ApiConstants} from "@/apis/constants";
import {login} from "@/apis/user";
import {
    errorMessage,
    successMessage
} from "@/common/components/Message";
import {
    setTokenAction,
    setUsernameAction
} from "@/redux/actions/user.action";
import {navigation} from "@/common/components/Navigation";

const {Password} = Input
const {Item} = Form

interface Props {
    changeActive: Function
    setUsername: Function
    setToken: Function
}

const rule = {
    username: [{required: true, message: "请输入用户名"}],
    password: [{required: true, message: "请输入密码"}]
}

/**
 * @Description: 登录ui组件
 * @author zhaojiuyi
 * @date 2023/4/14
 */
function MyLoginComponent(props: Props) {
    const changeActive = () => props.changeActive()
    const [username, setUsername] = useState<string>("")
    const [password, setPassword] = useState<string>("")

    const loginHandler = async (): Promise<void> => {
        const {code, data, msg} = await login({username, password})
        if (code === ApiConstants.SUCCESS) {
            props.setUsername(username)
            props.setToken(data)
            successMessage("登录成功")
            navigation("/index")
        } else {
            errorMessage(msg)
        }

    }

    return (
        <>
            <Card style={{width: 400, marginTop: 16}}>
                <h2>登录</h2>
                <Form name="loginForm" onFinish={loginHandler} autoComplete="off">
                    <Item name="username" rules={rule.username}>
                        <Input className="input" value={username} onChange={(e) => setUsername(e.target.value)}
                               placeholder="username" prefix={<UserOutlined/>}/>
                    </Item>
                    <Item name="password" rules={rule.password}>
                        <Password
                            className="input"
                            placeholder="password"
                            type="password"
                            prefix={<LockOutlined/>}
                            value={password} onChange={(e) => setPassword(e.target.value)}
                            iconRender={(visible) => (visible ? <EyeTwoTone/> : <EyeInvisibleOutlined/>)}/>
                    </Item>
                    <Item>
                        <Button type="primary" htmlType="submit" className="login_button">登录</Button>
                    </Item>
                </Form>
                <p>没有账号？<Button type="link" onClick={changeActive}>注册</Button></p>
            </Card>
        </>

    )

}

export const MyLogin = connect(
    state => ({}),
    {
        setUsername: setUsernameAction,
        setToken: setTokenAction
    }
)(MyLoginComponent)
